/**
 * author:Administrator
 * date:2016/3/16
 * desc: 地区信息
 * 地区信息全部采用应用缓存（上限）
 * 660个城市 * 20个区 * 50个街道 * 每条地址信息 100byte = 66M内存
 * 现在 mongodb中 7400条 ~ 0.7M
 */

"use strict";

let RawQuery = require('./_RawQuery.js');


class LoctionQuery extends RawQuery {
  constructor() {
    super();
  }

  * findAll() {
    //let sql = "select * from location";
    //return yield this.query(sql);
    yield this.__initCache();
    return cachedItem;
  }

  * findRoot() {
    //let sql = "select * from location where pid = 0";
    //return yield this.query(sql);
    yield this.__initCache();
    let ids = Object.keys(idTree);
    return cachedItem.filter(item => ids.indexOf(item.id) > 0);
  }

  * findChild(pid) {
    let sql = "select * from location where pid = '%pid'";
    sql = sql.replace('%pid', pid);
    return yield this.query(sql);
  }

  //
  * __initCache(forceInvalid) {
    if (!forceInvalid && LoctionQuery.cachedItem) {
      return;
    }

    let sql = "select * from location";
    let cachedItem = yield this.query(sql);
    cachedItem = Object.freeze(cachedItem);

    // build id tree
    let idTree = {};
    let remains = cachedItem.map(item => {
      return {id: item.id, pid: item.pid}
    });

    // TODO
    while (remains.length > 0) {
      let item = remains.pop();
      let ids = idPath(item.id);

      let pItem = idTree;
      while (ids.length > 0) {
        let id = ids.pop();
        if (!pItem[id]) pItem[id] = {};
        pItem = pItem[id];
      }
    }

    // 寻找该id 到 root之间的一条路径
    function idPath(id) {
      let arr = [id];
      let item = cachedItem.filter(o => o.id == id)[0];
      let pid = item.pid;
      while (pid != LoctionQuery.rootPid) {
        item = cachedItem.filter(o => o.id == pid)[0];
        arr.push(pid);
        pid = item.pid;
      }
      return arr;
    }

    idTree = Object.freeze(idTree);
    LoctionQuery.cachedItem = cachedItem;
    LoctionQuery.idTree = idTree;
  }
}

let cachedItem = null;  // 保存每条数据信息
let idTree = {};      // 仅保存树状结构id
let rootPid = 0;      // rootPid

LoctionQuery.cachedItem = cachedItem;
LoctionQuery.idTree = idTree;
LoctionQuery.rootPid = rootPid;

module.exports = new LoctionQuery();
